/**
 * Project Name:template-web
 * File Name   :ExpiresCacheFilter.java
 * Package Name:org.cn.template.component.web.filter
 * Date:2015年9月27日下午4:34:18
 * Copyright (c) 2015, http://my.oschina.net/httpssl All Rights Reserved.
 *
*/

package org.cn.template.component.web.filter;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * ClassName:ExpiresCacheFilter <br/>
 * Function :TODO ADD FUNCTION. <br/>
 * Reason	:TODO ADD REASON. <br/>
 * Date     :2015年9月27日 下午4:34:18 <br/>
 * @author  :http://my.oschina.net/httpssl
 * @email   :491835898@QQ.COM
 * @since   :JDK 1.7
 * @see 	 
 */
public class ExpiresCacheFilter implements Filter
{

	private FilterConfig config = null;
	private HashMap<String,Object> expiresMap = new HashMap<String,Object>();
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.config = filterConfig;
		expiresMap.clear();
		Enumeration<?> names = config.getInitParameterNames();
		while (names.hasMoreElements()) {
			try {
				String name = (String) names.nextElement();
				String value = config.getInitParameter(name);
				Integer expire = Integer.valueOf(value);
				expiresMap.put(name, expire);
			} catch (Exception ex) {
			}
		}
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		String uri = req.getRequestURI();
		String ext = null;
		int dot = uri.lastIndexOf(".");
		if (dot != -1) {
			ext = uri.substring(dot + 1);
		}
		setResponseHeader(res, uri, ext);
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		
	}
	private void setResponseHeader(HttpServletResponse response, String uri, String ext) {
		if (ext != null && ext.length() > 0) {
			Integer expires = (Integer) expiresMap.get(ext);
			if (expires != null) {
				if (expires.intValue() > 0) {
					response.setHeader("Cache-Control", "max-age=" + expires.intValue()); // HTTP
				} else {
					response.setHeader("Cache-Control", "no-cache");
					response.setHeader("Pragma", "no-cache"); // HTTP 1.0
					response.setDateHeader("Expires", 0);
				}
			}
		}
	}

}
